package algorithm;

/**
 * 交替打印
 */
public class ThreadPrintDemo {

  public static void main(String[] args) {

    ThreadPrintDemo printDemo = new ThreadPrintDemo();

    printDemo.doPrint(3);
  }

  public void doPrint(int l) {
    Object A = new Object();
    Object B = new Object();
    Object C = new Object();
    Print a = new Print("A", C, A, l);
    new Thread(a).start();

    Print b = new Print("B", A, B, l);
    new Thread(b).start();

    Print c = new Print("C", B, C, l);
    new Thread(c).start();

  }

  static class Print implements Runnable {

    String print;
    Object pre;
    Object self;
    int count;

    public Print(String print, Object pre, Object self, int l) {
      this.print = print;
      this.pre = pre;
      this.self = self;
      this.count = l;
    }

    public void run() {

      for (int i = 0; i < this.count; i++) {
        //锁住 上一个任务的对象锁
        synchronized (pre) {
          //锁住 自己任务的对象所
          synchronized (self) {
            System.out.println(Thread.currentThread().getName() + " " + print);
            //唤醒 下一个任务
            self.notify();
        }
        try {
          //阻塞 等待被上一个任务的对象锁 唤醒
          pre.wait();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        }

      }

    }


  }

}
